package com.camel.docker.service.impl;

import com.camel.docker.config.WebSocketServer;
import com.camel.docker.entity.Result;
import com.camel.docker.entity.search.ContainerAddForm;
import com.camel.docker.enums.ResultEnum;
import com.camel.docker.service.ContainerCreatorService;
import com.camel.docker.service.DockerClientService;
import com.camel.docker.task.CreatContainerFromGitTask;
import com.camel.docker.utils.DockerClientExceptionUtils;
import com.camel.docker.utils.DockerUtils;
import com.camel.docker.utils.ResultUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Slf4j
@Service
public class ContainerCreatorServiceImpl implements ContainerCreatorService {


    @Autowired
    public WebSocketServer webSocketServer;

    @Autowired
    public DockerClientService dockerClientService;

    @Override
    public Result creatFromFileSystem(ContainerAddForm containerAddForm) {
        // 获取客户端
        DockerClient client = dockerClientService.connect();

        CreateContainerResponse response = null;
        try {
            response = DockerUtils.getInstance().createContainer(containerAddForm, client);
        } catch (Exception e) {
            return DockerClientExceptionUtils.trans(e.getMessage(), containerAddForm);
        }
        Log4JLoggerFactory.getInstance(this.getClass()).info(response.toString());

        // 如果配置并创建成功，启动容器
        if (!StringUtils.isEmpty(response.getId())) {
            client.startContainerCmd(response.getId()).exec();
            return ResultUtil.success("创建容器成功");
        } else {
            return ResultUtil.error(ResultEnum.NOT_VALID_PARAM, "创建容器失败");
        }
    }

    @Override
    public Result creatFromGit(ContainerAddForm containerAddForm) {
        CreatContainerFromGitTask creatContainerFromGitTask = new CreatContainerFromGitTask(webSocketServer, containerAddForm, dockerClientService);
        creatContainerFromGitTask.start();
        return ResultUtil.success("一个容器正在创建");
    }

}
